package com.gange.controller;

import com.gange.entity.Video;
import com.gange.service.IVideoService;
import com.gange.utils.JSONUtils;
import com.gange.utils.VideoUtils;
import com.gange.vo.VideoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class VideoServiceController {
    @Autowired
    private IVideoService videoService;
    @Autowired
    private VideoUtils videoUtils;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 保存视频
     */
    @PostMapping("publish")
    public Video publish(@RequestBody Video video){
        log.info("接收到的video: {}", JSONUtils.writeValueAsString(video));
        video.setCreatedAt(LocalDateTime.now());
        video.setUpdatedAt(LocalDateTime.now());
        videoService.save(video);
        //发送消息到消息队列
        VideoVO videoVO = videoUtils.videoToVideovo(video);
        //2.发出消息
        rabbitTemplate.convertAndSend("X","ES",JSONUtils.writeValueAsString(videoVO));
        return video;
    }

    /**
     * 根据视频id查询视频的方法
     */
    @GetMapping("getVideos")
    public List<VideoVO> getVideos(@RequestParam("ids") List<Integer> ids){
        List<VideoVO> videoVOS = new ArrayList<>();
        log.info("ids: {}",ids);
        ids.forEach(id->{
            Video video = videoService.getById(id);
            videoVOS.add(videoUtils.videoToVideovo(video));
        });
        return videoVOS;
    }

}